package com.dragonwu.filter;

import com.alibaba.fastjson.JSON;
import com.dragonwu.constant.Constants;
import com.dragonwu.model.OnlineUser;
import com.dragonwu.model.R;
import com.dragonwu.utils.JwtUtil;
import com.dragonwu.utils.RedisUtil;
import com.dragonwu.utils.WebUtil;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * token验证过滤器
 *
 * @author DragonWu
 * @since 2022-10-07 19:02
 **/
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    public static final String HEADER = "Authorization";
    public static final String PARAM = "token";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获得前端请求中的token
        String token = request.getHeader(HEADER);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(PARAM);
        }
        //如果token为空，放行，验证失败
        if (StringUtils.isBlank(token)) {
            chain.doFilter(request, response);
            return;
        }

        //解析token
        Map<String, Object> claims = JwtUtil.parseJwt(token);
        if (Objects.isNull(claims)) {//解析异常
            R<String> result = R.restResult(null, HttpStatus.FORBIDDEN.value(), "token非法");
            String json = JSON.toJSONString(result);
            //返回解析错误的json数据
            WebUtil.renderString(response, json);
            return;
        }

        //获取用户主键，以便到redis中查询
        String primaryKey = (String) claims.get(JwtUtil.JWT_PRIMARY_KEY);
        //从redis中获取token对应的数据
        String redisKey = Constants.ONLINE_PRE + primaryKey;
        //获取用户信息
        OnlineUser onlineUser = (OnlineUser) redisUtil.getObject(redisKey);
        if (Objects.isNull(onlineUser)) {
            R<String> result = R.restResult(null, HttpStatus.UNAUTHORIZED.value(), "认证失败");
            String json = JSON.toJSONString(result);
            //返回请求失败的json数据
            WebUtil.renderString(response, json);
            return;
        }

        //存入SecurityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(onlineUser, null,
                        AuthorityUtils.commaSeparatedStringToAuthorityList(onlineUser.getAuthorities()));
        //获取权限信息封装到authenticationToken里
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        chain.doFilter(request, response);

    }
}
